<template>
  <view class="login-container">
    <!-- Logo区域 -->
    <view class="logo-section">
      <image class="logo" src="/static/images/logo.png" />
      <text class="app-name">智慧社区</text>
      <text class="app-subtitle">让生活更智能</text>
    </view>
    
    <!-- 登录表单 -->
    <view class="login-form">
      <u-form :model="loginForm" ref="formRef" :rules="formRules">
        <!-- 身份选择 -->
        <u-form-item prop="loginIdentityType">
          <u-picker 
            :show="showIdentityPicker"
            :columns="identityColumns"
            @confirm="onIdentityConfirm"
            @cancel="showIdentityPicker = false"
          />
          <view class="identity-input" @click="showIdentityPicker = true" :style="inputStyle">
            <text class="identity-text">{{ loginForm.identityTypeName || '请选择登录身份' }}</text>
            <view class="identity-arrow">
              <u-icon name="arrow-down" size="16" color="#999" />
            </view>
          </view>
        </u-form-item>
        
        <u-form-item prop="username">
          <u-input 
            v-model="loginForm.username"
            placeholder="请输入账号"
            :clearable="true"
            border="false"
            :customStyle="inputStyle"
          >
            <template #prefix>
              <u-icon name="account-fill" size="18" color="#666" style="margin-right: 8px;" />
            </template>
          </u-input>
        </u-form-item>
        
        <u-form-item prop="password">
          <u-input 
            v-model="loginForm.password"
            placeholder="请输入密码"
            :password="!showPassword"
            border="false"
            :customStyle="inputStyle"
          >
            <template #prefix>
              <u-icon name="lock-fill" size="18" color="#666" style="margin-right: 8px;" />
            </template>
          </u-input>
        </u-form-item>
        
        <u-form-item prop="captcha" v-if="showCaptcha">
          <view class="captcha-container">
            <u-input 
              v-model="loginForm.captcha"
              placeholder="验证码"
              :maxlength="4"
              class="captcha-input"
              border="false"
              :customStyle="inputStyle"
            >
              <template #prefix>
                <u-icon size="18" color="#666" style="margin-right: 8px;" />
              </template>
            </u-input>
            <view class="captcha-display" @click="getCaptcha">
              <view v-if="captchaCode" class="captcha-number">
                {{ captchaCode }}
              </view>
              <view v-else class="captcha-placeholder">
                <u-icon name="refresh" size="16" color="#999" />
                <text class="refresh-text">点击刷新</text>
              </view>
            </view>
          </view>
        </u-form-item>
        
        <u-form-item>
          <u-checkbox-group v-model="checkboxGroupValue">
            <u-checkbox label="记住密码" shape="circle">
              <text class="checkbox-label">记住密码</text>
            </u-checkbox>
            <u-checkbox label="自动登录" shape="circle">
              <text class="checkbox-label">自动登录</text>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        
        <u-button 
          type="primary"
          :loading="loginLoading"
          @click="handleLogin"
          :customStyle="buttonStyle"
        >
          {{ loginLoading ? '登录中...' : '登录' }}
        </u-button>
      </u-form>
    </view>
    
    <!-- 辅助功能 -->
    <view class="login-options">
      <view class="quick-login">
        <text class="option-title">其他登录方式</text>
        <view class="login-icons">
          <view class="icon-item" @click="wechatLogin">
            <u-icon name="weixin-fill" size="24" color="#07c160" />
          </view>
          <view class="icon-item" @click="fingerprintLogin" v-if="biometricSupported">
            <u-icon name="fingerprint" size="24" color="#2d8cf0" />
          </view>
          <view class="icon-item" @click="phoneLogin">
            <u-icon name="phone-fill" size="24" color="#ff6b35" />
          </view>
        </view>
      </view>
      
      <view class="bottom-links">
        <text @click="forgotPassword">忘记密码</text>
        <text class="divider">|</text>
        <text @click="goToRegister">注册账号</text>
        <text class="divider">|</text>
        <text @click="goToCompanyRegister">物业公司注册</text>
      </view>
    </view>
  </view>
</template>

<script setup>
/**
 * 登录页面
 * @author Wu.Liang
 * @date 2025-01-21
 */

import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useAuthStore } from '@/store'

const authStore = useAuthStore()
const formRef = ref(null)
const loginLoading = ref(false)
const showPassword = ref(false)
const showCaptcha = ref(false)
const captchaCode = ref('')
const biometricSupported = ref(false)
const checkboxGroupValue = ref([])
const showIdentityPicker = ref(false)

watch(checkboxGroupValue, (val) => {
  loginForm.rememberPassword = val.includes('记住密码')
  loginForm.autoLogin = val.includes('自动登录')
})

// 身份选择配置
const identityColumns = ref([
  [
    { text: '房产业主登录', value: 1 },
    { text: '物业管理登录', value: 2 },
    { text: '普通用户登录', value: 3 }
  ]
])

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  captchaKey: '',
  loginIdentityType: 1, // 默认选择房产业主登录
  identityTypeName: '房产业主登录',
  rememberPassword: false,
  autoLogin: false
})

// 表单验证规则
const formRules = {
  loginIdentityType: [
    { required: true, message: '请选择登录身份' }
  ],
  username: [
    { required: true, message: '请输入账号' },
    { min: 3, message: '账号长度不能少于3位' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, message: '密码长度不能少于6位' }
  ],
  captcha: [
    { required: true, message: '请输入验证码' },
    { pattern: /^\d{4}$/, message: '请输入4位数字验证码' }
  ]
}

// 样式配置
const inputStyle = computed(() => ({
  backgroundColor: '#f8f9fa',
  borderRadius: '8px',
  padding: '12px 16px',
  fontSize: '16px',
  height: '48px'
}))

const buttonStyle = computed(() => ({
  backgroundColor: '#2d8cf0',
  borderRadius: '8px',
  height: '48px',
  fontSize: '16px',
  fontWeight: '600'
}))

// 身份选择确认
const onIdentityConfirm = (e) => {
  const selectedItem = e.value[0]
  loginForm.loginIdentityType = selectedItem.value
  loginForm.identityTypeName = selectedItem.text
  showIdentityPicker.value = false
}

// 获取验证码
const getCaptcha = async () => {
  try {
    const response = await authStore.getCaptcha('login')
    if (response.code === 200) {
      captchaCode.value = response.data.captcha
      loginForm.captchaKey = response.data.captchaKey
      showCaptcha.value = true
      uni.showToast({
        title: '验证码已获取',
        icon: 'success'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none'
    })
  }
}

// 处理登录
const handleLogin = async () => {
  try {
    await formRef.value.validate()
    loginLoading.value = true
    
    const loginData = {
      username: loginForm.username,
      password: loginForm.password,
      loginIdentityType: loginForm.loginIdentityType
    }
    
    if (showCaptcha.value) {
      loginData.captcha = loginForm.captcha
      loginData.captchaKey = loginForm.captchaKey
    }
    
    await authStore.appLogin(loginData)
    
    // 保存记住密码
    if (loginForm.rememberPassword) {
      uni.setStorageSync('remembered_username', loginForm.username)
      uni.setStorageSync('remembered_password', loginForm.password)
    } else {
      uni.removeStorageSync('remembered_username')
      uni.removeStorageSync('remembered_password')
    }
    
    // 设置自动登录
    authStore.setAutoLogin(loginForm.autoLogin)
    
    // 清除登录失败次数
    uni.removeStorageSync('login_fail_count')
    
    uni.showToast({ title: '登录成功', icon: 'success' })
    
    // 跳转到首页
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index/index' })
    }, 1500)
    
  } catch (error) {
    console.error('登录失败:', error)
    
    // 增加登录失败次数
    const failCount = (uni.getStorageSync('login_fail_count') || 0) + 1
    uni.setStorageSync('login_fail_count', failCount)
    
    // 如果登录失败超过3次，显示验证码
    if (failCount >= 3 && !showCaptcha.value) {
      showCaptcha.value = true
      getCaptcha()
    }
    
    uni.showToast({ 
      title: error.message || '登录失败，请稍后重试', 
      icon: 'error' 
    })
    
    // 登录失败时自动刷新验证码
    if (showCaptcha.value) {
      await getCaptcha()
    }
  } finally {
    loginLoading.value = false
  }
}

// 微信登录
const wechatLogin = () => {
  uni.showToast({ title: '微信登录功能开发中', icon: 'none' })
}

// 生物识别登录
const fingerprintLogin = () => {
  if (!biometricSupported.value) {
    uni.showToast({ title: '设备不支持生物识别', icon: 'none' })
    return
  }
  
  uni.startSoterAuthentication({
    requestAuthModes: ['fingerPrint'],
    challenge: 'login',
    authContent: '请验证指纹',
    success: () => {
      // 生物识别成功，自动登录
      handleBiometricLogin()
    },
    fail: () => {
      uni.showToast({ title: '指纹验证失败', icon: 'error' })
    }
  })
}

// 生物识别登录处理
const handleBiometricLogin = async () => {
  try {
    // 使用存储的生物识别凭证登录
    await authStore.biometricLogin()
    uni.showToast({ title: '登录成功', icon: 'success' })
    uni.switchTab({ url: '/pages/index/index' })
  } catch (error) {
    uni.showToast({ title: '生物识别登录失败', icon: 'error' })
  }
}

// 手机登录
const phoneLogin = () => {
  uni.navigateTo({ url: '/pages/login/phone-login' })
}

// 忘记密码
const forgotPassword = () => {
  uni.navigateTo({ url: '/pages/login/forgot-password' })
}

// 注册账号
const goToRegister = () => {
  uni.navigateTo({ url: '/pages/register/register' })
}

// 物业公司注册
const goToCompanyRegister = () => {
  uni.navigateTo({ url: '/pages/property/company-register' })
}

// 检查生物识别支持
const checkBiometricSupport = () => {
  // 检查是否支持生物识别
  // #ifdef APP-PLUS
  uni.checkIsSupportSoterAuthentication({
    success: (res) => {
      if (res.supportMode && res.supportMode.includes('fingerPrint')) {
        biometricSupported.value = true
        console.log('支持指纹识别')
      }
    },
    fail: (err) => {
      console.log('不支持生物识别:', err)
      biometricSupported.value = false
    }
  })
  // #endif
  
  // #ifdef H5
  // H5环境不支持生物识别
  biometricSupported.value = false
  console.log('H5环境不支持生物识别')
  // #endif
  
  // #ifdef MP
  // 小程序环境不支持生物识别
  biometricSupported.value = false
  console.log('小程序环境不支持生物识别')
  // #endif
}

// 页面加载时初始化
onMounted(() => {
  // 检查是否有记住的用户名密码
  const rememberedUsername = uni.getStorageSync('remembered_username')
  const rememberedPassword = uni.getStorageSync('remembered_password')
  
  if (rememberedUsername && rememberedPassword) {
    loginForm.username = rememberedUsername
    loginForm.password = rememberedPassword
    loginForm.rememberPassword = true
  }
  
  // 检查是否需要显示验证码
  const loginFailCount = uni.getStorageSync('login_fail_count') || 0
  if (loginFailCount >= 3) {
    showCaptcha.value = true
    getCaptcha()
  }
  
  // 检查生物识别支持
  checkBiometricSupport()
  
  // 获取初始验证码
  getCaptcha()

  // 初始化checkbox状态
  const arr = []
  if (loginForm.rememberPassword) arr.push('记住密码')
  if (loginForm.autoLogin) arr.push('自动登录')
  checkboxGroupValue.value = arr
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 24px;
}

.logo-section {
  margin-top: 80px;
  text-align: center;
  
  .logo {
    width: 80px;
    height: 80px;
    margin-bottom: 16px;
  }
  
  .app-name {
    font-size: 24px;
    font-weight: bold;
    color: white;
    display: block;
    margin-bottom: 8px;
  }
  
  .app-subtitle {
    font-size: 16px;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-form {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-top: 40px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.identity-input {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 12px 16px;
  font-size: 16px;
  height: 48px;
  cursor: pointer;
  border: 1px solid transparent;
  transition: all 0.3s ease;
}

.identity-input:hover {
  border-color: #2d8cf0;
  background-color: #f0f8ff;
}

.identity-text {
  flex: 1;
  color: #333;
  font-size: 16px;
}

.identity-arrow {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .captcha-input {
    flex: 1;
  }
  
  .captcha-display {
    width: 120px;
    height: 48px;
    border-radius: 8px;
    background: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border: 1px solid #e9ecef;
    
    .captcha-number {
      font-size: 18px;
      font-weight: bold;
      color: #2d8cf0;
      letter-spacing: 2px;
    }
    
    .captcha-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;
      
      .refresh-text {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .checkbox-label {
    font-size: 14px;
    color: #666;
    margin-left: 8px;
  }
}

.login-options {
  margin-top: 40px;
  width: 100%;
  max-width: 400px;
  
  .quick-login {
    text-align: center;
    margin-bottom: 32px;
    
    .option-title {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
      margin-bottom: 16px;
      display: block;
    }
    
    .login-icons {
      display: flex;
      justify-content: center;
      gap: 24px;
      
      .icon-item {
        width: 48px;
        height: 48px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(255, 255, 255, 0.3);
          transform: scale(1.1);
        }
      }
    }
  }
  
  .bottom-links {
    text-align: center;
    
    text {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
      cursor: pointer;
      transition: color 0.3s ease;
      
      &:hover {
        color: white;
      }
    }
    
    .divider {
      margin: 0 12px;
      color: rgba(255, 255, 255, 0.5);
    }
  }
}
</style> 